package com.dcy.znoa.common.util.excel;

/**
 * Created by pengyu on 2017/11/3.
 */

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class HttpUtil {
    private static final String ISO_8859_1_CHARSET = "iso-8859-1";
    private static final String JAVA_CHARSET = "utf-8";

    public HttpUtil() {
    }

    public static String urlEncode(String value, String charset) throws UnsupportedEncodingException {
        return value != null?URLEncoder.encode(value, charset).replace("+", "%20").replace("*", "%2A").replace("%7E", "~"):null;
    }

    public static String paramToQueryString(Map<String, String> params, String charset) throws UnsupportedEncodingException {
        if(params != null && params.size() != 0) {
            StringBuilder paramString = new StringBuilder();
            boolean first = true;

            for(Iterator i$ = params.entrySet().iterator(); i$.hasNext(); first = false) {
                Entry p = (Entry)i$.next();
                String key = (String)p.getKey();
                String val = (String)p.getValue();
                if(!first) {
                    paramString.append("&");
                }

                paramString.append(key);
                if(val != null) {
                    paramString.append("=").append(urlEncode(val, charset));
                }
            }

            return paramString.toString();
        } else {
            return null;
        }
    }

    public static void convertHeaderCharsetFromIso88591(Map<String, String> headers) {
        convertHeaderCharset(headers, "iso-8859-1", "utf-8");
    }

    public static void convertHeaderCharsetToIso88591(Map<String, String> headers) {
        convertHeaderCharset(headers, "utf-8", "iso-8859-1");
    }

    private static void convertHeaderCharset(Map<String, String> headers, String fromCharset, String toCharset) {
        assert headers != null;

        Iterator i$ = headers.entrySet().iterator();

        while(i$.hasNext()) {
            Entry header = (Entry)i$.next();
            if(header.getValue() != null) {
                try {
                    header.setValue(new String(((String)header.getValue()).getBytes(fromCharset), toCharset));
                } catch (UnsupportedEncodingException var6) {
                    throw new AssertionError("Invalid charset name.");
                }
            }
        }

    }
}

